import os
import mindspore
from mindspore import Model, context
import ipywidgets as wgs

dropdown = wgs.Dropdown(description='Selcet Device', options=['Click to choose', "CPU", 'Ascend NPU'])
output = wgs.Output()


def changeDevice(change):
    output.clear_output()
    token = change.new
    with output:
        if token == 'Click to choose':
            print('请选择运行环境')
        if token == 'CPU':
            print('请确认当前环境为CPU\n==============')
            try:
                context.set_context(mode=context.GRAPH_MODE, device_target='CPU', save_graphs=False)
                print('已检查，确认当前环境为CPU')
            except ValueError:
                print('错误！当前的系统硬件不是CPU，请重新选择合适的硬件设备')
        if token == 'Ascend NPU':
            print('请确认当前环境为Ascend NPU\n==============')
            try:
                context.set_context(mode=context.GRAPH_MODE, device_target='Ascend', save_graphs=False)
                print('已检查，确认当前环境为Ascend NPU')
            except ValueError:
                print('错误！当前的系统硬件不是Ascend NPU，请重新选择合适的硬件设备')


dropdown.observe(changeDevice, names='value')
# display(dropdown,output)

# cpu的参数设置
device_id = 2
epochs = 2
resume = True
per_print_times = 1
resume_ckpt = './checkpoints/pretrained.ckpt'

import os
import requests
import time
import zipfile


def download_and_zip(url, path):
    if not os.path.exists(path):
        os.mkdir(path)
    file_path = os.path.join(path, 'case7BrainMRI.zip')
    start = time.time()
    user, password = 'tyx_neu', 'Sportlab307'
    resp = requests.get(url, auth=(user, password), stream=True)
    size = 0
    chunk_size = 1024
    content_size = int(resp.headers['content-length'])

    try:
        if resp.status_code == 200:
            print('start download [file size]:{size:.2f}MB'.format(size=content_size / chunk_size / 1024))
            with open(file_path, 'wb') as file:
                for data in resp.iter_content(chunk_size == chunk_size):
                    file.write(data)
                    size += len(data)
                    print('\r' + '[下载进度]:%s%.2f%%' % (
                        '>' * int(size * 50 / content_size), float(size / content_size * 100)), end=' ')
        end = time.time()
        print('\n' + 'download completed, time:%.2f秒' % (end - start))
    except ValueError:
        print('error')

    unzip_file_path = os.path.join(path, 'case7BrainMRI')
    if not os.path.exists(unzip_file_path):
        os.mkdir(unzip_file_path)

    zip_file = zipfile.ZipFile(file_path)
    zip_list = zip_file.namelist()
    for f in zip_list:
        zip_file.extract(f, unzip_file_path)
    zip_file.close()
    print('successly unzip download flower dataset from website')


# # if you download this data, so those two lines of code needn't  be executed.
# ur1 = 'https://openi.pcl.ac.cn/attachments/e8ac2afb-e189-47aa-b916-f0be50b737a8?type=1'
# download_and_zip(ur1, 'dataset')
